'use strict';

const Controller = require('egg').Controller;
const utility = require("utility") //密码加密

class HomeController extends Controller {
  async register() {
    const { ctx, service } = this;
    let { userName, passWord, role } = ctx.request.body;
    if (!role) role = 1;
    let res = await service.add.addUser({ userName, passWord, role });
    // console.log(res)
    this.ctx.body = res;
  }

  async login() {
    const { ctx, app } = this;
    let { userName, passWord } = ctx.request.body;
    let FindArr = await ctx.model.User.findOne({ userName: userName, passWord: await utility.md5(passWord), role: { $gte: 0 } });
    if (!FindArr) return this.ctx.body = { code: 203, msg: '用户名或密码错误！' };
    if (FindArr.role == -1) return this.ctx.body = { code: 204, msg: '账号已被注销！' };
    // 跟新用户最新的登陆时间
    await ctx.model.User.updateOne({ userName: userName, passWord: await utility.md5(passWord) }, { updateTime: Date.now() });
    // 调用 rotateCsrfSecret 刷新用户的 CSRF token
    // 签发token
    const token = await app.jwt.sign({
      userName: FindArr.userName,
      passWord: FindArr.passWord,
      role: FindArr.role
    },
      this.config.jwt.secret, {
      expiresIn: 24 * 60 * 60,
    });

    // 请求头中的 token
    // const token = ctx.request.header.authorization;

    // ctx.body = { success: true };

    ctx.body = { token: token, FindArr, code: 200, msg: '登陆成功' }
  }

  async cs() {
    const { ctx } = this;

    let obj = await ctx.model.ConsumeOrders.updateMany({}, { operation: 'admin', role: 0 });
    let o = { code: 200, data: JSON.stringify(obj) }
    // operation, role
    ctx.body = { code: 200, msg: 'OK' }
  }
}

module.exports = HomeController;
